﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Diagnostics;
using TRASOutlook.TRAServiceReference;

namespace TRASOutlook
{
    class CTaskMgr
    {
        private TRAServiceReference.ServiceClient TRASClient;

        /// <summary>
        /// 一个任务的关键字信息,
        /// 用于检查任务是否已经存放在任务列表中
        /// </summary>
        class TempTask : IEquatable<TempTask>
        {
            public int ID;
            public DateTime task_time;

            #region IEquatable<TempTask> Members

            public bool Equals(TempTask other)
            {
                return ID == other.ID && task_time == other.task_time;
            }

            #endregion
        }

        static CTaskMgr inst = null;
        public static CTaskMgr Instance()
        {
            if (inst == null)
                inst = new CTaskMgr();
            return inst;
        }

        

        public ThisAddIn Addin { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        private CTaskMgr()
        {
        }

        /// <summary>
        /// 检查并创建远程服务对象
        /// </summary>
        /// <returns></returns>
        public bool CheckServiceObject()
        {
            Debug.WriteLine(System.Configuration.ConfigurationSettings.AppSettings.Count);
            if (Properties.Settings.Default.ServerAddress.Length == 0)
                return false;

            if (TRASClient == null)
                TRASClient = new TRAServiceReference.ServiceClient("FirstConfigure", Properties.Settings.Default.ServerAddress);

            System.Diagnostics.Debug.WriteLine(TRASClient.Endpoint.Address.Uri);

            return true;

        }

        /// <summary>
        /// 同步任务列表,
        /// 遵照只创建不删除
        /// </summary>
        public void SynchronizeTasks()
        {
            if (!CheckServiceObject())
                return;

            List<TempTask> tempTasks = new List<TempTask>();

            Outlook.Folder taskList = Addin.Application.Session.GetDefaultFolder(
                    Outlook.OlDefaultFolders.olFolderTasks) as Outlook.Folder;

            foreach (object obj in taskList.Items)
            {
                Outlook.TaskItem taskItem = obj as Outlook.TaskItem;
                if (taskItem.MessageClass == "IPM.Task.PublishNews" ||
                    taskItem.MessageClass == "IPM.Task.BroadcastTask")
                {
                    if (taskItem.UserProperties["ID"] != null &&
                        taskItem.UserProperties["tasktime"] != null)
                    {
                        TempTask tempTask = new TempTask();
                        tempTask.ID = Convert.ToInt32(taskItem.UserProperties["ID"].Value);
                        tempTask.task_time = Convert.ToDateTime(taskItem.UserProperties["tasktime"].Value);
                        tempTasks.Add(tempTask);
                    }
                }
            }

            try
            {
                List<Task> tasks = TRASClient.GetTasks();
                foreach (Task task in tasks)
                {
                    TempTask tempTask = new TempTask();
                    tempTask.ID = task.ID;
                    tempTask.task_time = task.date;
                    if (tempTasks.Contains(tempTask))
                        continue;

                    if (task is Task_News)
                    {
                        CreateNewsTask(taskList, (Task_News)task);
                    }
                    else if (task is Task_Broadcast)
                    {
                        CreateBroadcastTask(taskList, (Task_Broadcast)task);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 建立任务(所有任务的共同属性)
        /// </summary>
        /// <param name="taskItem"></param>
        /// <param name="task"></param>
        void CreateTask(Outlook.TaskItem taskItem, Task task)
        {
            if (task.everyday_task)
            {
                taskItem.StartDate = task.date;
                taskItem.DueDate = task.date;
            }
            else
            {
                taskItem.StartDate = task.start_time;
                taskItem.DueDate = task.end_time;
            }
            taskItem.Subject = task.description;
            taskItem.Status = Microsoft.Office.Interop.Outlook.OlTaskStatus.olTaskInProgress;
            taskItem.Importance = (Microsoft.Office.Interop.Outlook.OlImportance)(task.level + 1);

            Outlook.UserProperty coordinateProperty = taskItem.UserProperties.Add("coordinator", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            coordinateProperty.Value = task.coordinator;

            Outlook.UserProperty operatorProperty = taskItem.UserProperties.Add("operator", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            operatorProperty.Value = task.operater;

            Outlook.UserProperty IDProperty = taskItem.UserProperties.Add("ID", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olInteger, false, false);
            IDProperty.Value = task.ID;

            Outlook.UserProperty tasktimeProperty = taskItem.UserProperties.Add("tasktime", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olDateTime, false, false);
            tasktimeProperty.Value = task.date;
        }

        /// <summary>
        /// 创建新闻任务
        /// </summary>
        /// <param name="taskList"></param>
        /// <param name="task"></param>
        void CreateNewsTask(Outlook.Folder taskList, Task_News task)
        {
            Outlook.TaskItem taskItem = taskList.Items.Add("IPM.Task.PublishNews") as Outlook.TaskItem;
            CreateTask(taskItem, task);

            Outlook.UserProperty titleProperty = taskItem.UserProperties.Add("title", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            titleProperty.Value = task.title;

            Outlook.UserProperty linkProperty = taskItem.UserProperties.Add("linkaddr", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            linkProperty.Value = task.link_addr;

            Outlook.UserProperty memoProperty = taskItem.UserProperties.Add("memo", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            memoProperty.Value = task.memo;

            taskItem.Save();
        }

        /// <summary>
        /// 创建公告任务
        /// </summary>
        /// <param name="taskList"></param>
        /// <param name="task"></param>
        void CreateBroadcastTask(Outlook.Folder taskList, Task_Broadcast task)
        {
            Outlook.TaskItem taskItem = taskList.Items.Add("IPM.Task.BroadcastTask") as Outlook.TaskItem;
            CreateTask(taskItem, task);

            Outlook.UserProperty contentProperty = taskItem.UserProperties.Add("content", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            contentProperty.Value = task.content;

            Outlook.UserProperty serverProperty = taskItem.UserProperties.Add("servers", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            serverProperty.Value = task.servers;

            Outlook.UserProperty memoProperty = taskItem.UserProperties.Add("memo", Microsoft.Office.Interop.Outlook.OlUserPropertyType.olText, false, false);
            memoProperty.Value = task.memo;

            taskItem.Save();
        }

        public void CompleteNewsTask(Outlook.TaskItem task)
        {
            if (!CheckServiceObject())
            {
                System.Windows.Forms.MessageBox.Show("服务器配置错误", "错误", 
                    System.Windows.Forms.MessageBoxButtons.OK, 
                    System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }
            
            try
            {
                if (task.UserProperties["title"] == null)
                    return;
                if (task.UserProperties["memo"] == null)
                    return;
                if (task.UserProperties["linkaddr"] == null)
                    return;
                if (task.UserProperties["ID"] == null)
                    return;
                if (task.UserProperties["tasktime"] == null)
                    return;

                int ID = Convert.ToInt32(task.UserProperties["ID"].Value);
                DateTime date = Convert.ToDateTime(task.UserProperties["tasktime"].Value);
                string title = task.UserProperties["title"].Value.ToString();
                string link = task.UserProperties["linkaddr"].Value.ToString();
                string memo = task.UserProperties["memo"].Value.ToString();
                TRASClient.NewsTaskFinish(ID, date, title, link, memo);
                task.Complete = true;
                task.Save();
            }
            catch (System.Exception ex)
            {
            	
            }

        }

    }
}
